package com.banksoft.admin.service.impl;

import com.banksoft.admin.bean.AmountType;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.dao.*;
import com.banksoft.admin.entity.*;
import com.banksoft.admin.service.PartnerApplyService;
import com.banksoft.common.ConfigHelper;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by vanjoger on 2017/1/5.
 */
@Service
@Transactional
public class PartnerApplyServiceImpl implements PartnerApplyService {

    @Autowired
    PartnerApplyDao partnerApplyDao;
    @Autowired
    BaseMyBatisDao baseMyBatisDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserMoneyDao userMoneyDao;
    @Autowired
    UserAddressDao userAddressDao;

    @Override
    public JSONObject save(String id, String status, String bz) {
        PartnerApply apply = this.baseMyBatisDao.findById(PartnerApplyDao.class,id);
        if(apply==null)
            return StringUtil.FmtResult(false,"没有找到数据",null);
        if(!apply.getStatus().equals("0"))
            return StringUtil.FmtResult(false,"该申请已被审核，无需再次审核",null);
        if("1".equals(status)){//审核通过时  需判断
            List<User> list = userDao.listUserByCity(apply.getUserLevel(), apply.getProvince(), apply.getCity(), apply.getArea());
            if (StringUtil.isNotEmpty(list)) {
                    return StringUtil.FmtResult(false,"该区域已有其他的区域合伙人，请重新选择",null);
            }
        }

        apply.setStatus(status);
        apply.setApplyTime(new Date().getTime());
        apply.setBz(bz);
        this.baseMyBatisDao.update(PartnerApplyDao.class,apply);

        if("1".equals(status)) {//审核通过后
            User user = baseMyBatisDao.findById(UserDao.class,apply.getUserId());
            //全国总代
            user.setType(MemberType.General.name());
            user.setIsPartner("1");
            user.setPartnerDate(new Date().getTime());
            user.setUserLevel(apply.getUserLevel());
            user.setUserProvince(apply.getProvince());
            user.setUserProvinceName(apply.getProvinceName());
            user.setUserCity(apply.getCity());
            user.setUserCityName(apply.getCityName());
            user.setUserArea(apply.getArea());
            user.setUserAreaName(apply.getAreaName());
            user.setIsMember("1");
            //用户类型变化后  其上级也发生变化 若其上级为普通消费者 将其剔除
            User upperUser = getUserUpper(user);
            if(user!=null&&upperUser!=null)
                //user.setRecommendId(upperUser.getOpenId());
                user.setRecommendId(upperUser.getId());
            this.baseMyBatisDao.update(UserDao.class, user);

            //给其上级计算区域合伙人返利
            //calMoney(upperUser);
        }

        return StringUtil.FmtResult(true,"审核成功",null);
    }

    /**
     * 计算升级返现
     * @param user
     */
    private void calMoney(User user){
        if(user.getType().equals(MemberType.Gold.name())||user.getType().equals(MemberType.General.name())) {
            ConfigHelper instance = ConfigHelper.GetInstance();
            String Member = instance.GetConfig("Member_Zjcd");
            String Partner_Fee = instance.GetConfig("Partner_Fee");
            String bonus = StringNumber.mul(Partner_Fee, Member);
            String cash = StringNumber.sub(Partner_Fee, bonus);

            List<UserMoney> moneys = userMoneyDao.findByUserId(user.getId());
            UserMoney money = null;
            if(StringUtil.isNotEmpty(moneys))
                money = moneys.get(0);
            boolean needSave = false;
            if (money == null) {
                money = new UserMoney();
                money.setId(UUIDFactory.random());
                money.setUserId(user.getId());
                money.setUserName(user.getNickName());
                needSave = true;
            }
            String beforeCash = money.getCash();
            String beforeBonus = money.getBonus();
            money.setCash(StringNumber.add(beforeCash,cash));
            money.setBonus(StringNumber.add(beforeBonus,bonus));
            money.setTotalAmount(StringNumber.add(StringNumber.add(money.getTotalAmount(),cash),bonus));
            if (needSave) {
                baseMyBatisDao.insert(UserMoneyDao.class, money);
            } else {
                baseMyBatisDao.update(UserMoneyDao.class, money);
            }
            //保存日志
            saveAmountLog(user, beforeCash + "", beforeBonus + "", cash, bonus, money.getCash() + "", money.getBonus() + "", AmountType.PartnerFee.name(),money.getFrozenAmount()+"");
        }
    }

    private void saveAmountLog(User user,String beforeCash,String beforeBonus,String cash,String bonus,String afterCash,String afterBonus,String type,String frozenAmount){
        AmountLog log = new AmountLog();
        log.setId(UUIDFactory.random());
        log.setUserId(user.getId());
        log.setUserName(user.getNickName());
        log.setCreateTime(new Date().getTime());
        log.setBeforeCash(beforeCash);
        log.setBeforeBonus(beforeBonus);
        log.setCash(cash);
        log.setBonus(bonus);
        log.setAfterCash(afterCash);
        log.setAfterBonus(afterBonus);
        log.setType(type);
        log.setBeforeFrozenAmount(frozenAmount);
        log.setAfterFrozenAmount(frozenAmount);
        baseMyBatisDao.insert(AmountLogDao.class,log);
    }

    /**
     * 将其上级为普通消费者的剔除
     * @param user
     */
    private User getUserUpper(User user) {
        User upUser = baseMyBatisDao.findById(UserDao.class,user.getRecommendId());
        if(upUser!=null) {
            if (!upUser.getType().equals(MemberType.Customer.name())) {//不等于普通消费者的话
                return upUser;
            } else {
                return getUserUpper(upUser);
            }
        }
        return null;
    }

    @Override
    public void saveParnterApply(String userId, String remark, String province, String provinceName, String city, String cityName,
                                 String area, String areaName, String userLevel, String userName, String telephone,
                                 String idCard, String bankName, String cardName, String cardNo,
                                 String addressProvince, String addressProvinceName, String addressCity,
                                 String addressCityName, String addressArea, String addressAreaName) {
        User user = baseMyBatisDao.findById(UserDao.class,userId);
        user.setIdCard(idCard);
        user.setBankName(bankName);
        user.setCardName(cardName);
        user.setCardNo(cardNo);
        user.setUserProvince(province);
        user.setUserProvinceName(provinceName);
        user.setUserCity(city);
        user.setUserCityName(cityName);
        user.setUserArea(area);
        user.setUserAreaName(areaName);
        this.baseMyBatisDao.update(UserDao.class,user);

        List<UserAddress> userAddresses = this.userAddressDao.listByUserId(userId);
        //如果存在此地区的收货地址
        boolean find = false;
        if(StringUtil.isNotEmpty(userAddresses)){
            for(UserAddress address:userAddresses){
                if(address.getArea().equals(addressArea)){
                    find = true;
                    address.setIsDefault("0");
                    address.setUserName(userName);
                    address.setTelephone(telephone);
                }else{
                    address.setIsDefault("1");
                }
                this.baseMyBatisDao.update(UserAddressDao.class,address);
            }
        }
        if(!find){
            UserAddress address = new UserAddress();
            address.setId(UUIDFactory.random());
            address.setUserId(user.getId());
            address.setUserName(user.getNickName());
            address.setTelephone(telephone);
            address.setProvince(addressProvince);
            address.setProvinceName(addressProvinceName);
            address.setCity(addressCity);
            address.setCityName(addressCityName);
            address.setArea(addressArea);
            address.setAreaName(addressAreaName);
            address.setIsDefault("0");
            this.baseMyBatisDao.insert(UserAddressDao.class,address);
        }

        PartnerApply apply = new PartnerApply();
        apply.setId(UUIDFactory.random());
        apply.setUserId(userId);
        apply.setUserNickName(user.getNickName());
        apply.setCreateTime(new Date().getTime());
        apply.setStatus("0");
        apply.setRemark(remark);
        apply.setProvince(province);
        apply.setProvinceName(provinceName);
        apply.setCity(city);
        apply.setCityName(cityName);
        apply.setArea(area);
        apply.setAreaName(areaName);
        apply.setUserLevel(userLevel);
        this.baseMyBatisDao.insert(PartnerApplyDao.class,apply);
    }


}
